<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;


class PlazaModel extends AbstractBaseModel
{


    const TYPE_JOB_POSITION = 1;
    const TYPE_AREA = 2;
    const TYPE_LIST = [
        self::TYPE_JOB_POSITION => '职位',
        self::TYPE_AREA => '专区',
    ];
    protected $table = 'plaza';

    protected $sortable = [
        // 设置排序字段名称
        'order_column_name' => 'sort',
        // 是否在创建时自动排序，此参数建议设置为true
        'sort_when_creating' => true,
    ];

    protected $casts = [
        'tags' => 'json',
    ];

    /**
     * 报名人数
     * @return int|mixed
     */
    public function applyNum()
    {
        if ($this->cur_type == self::TYPE_JOB_POSITION) {
            $num = $this->jobPositionInfo->recruit_num ?? 0;
        } else {
            $ids = AreaJobPositionModel::query()->where('plaza_id', $this->id)->pluck('job_position_id');
            $num = $ids ? JobpositionModel::query()->whereIn('id', $ids)->sum('recruit_num') : 0;
        }
        return $num;
    }

    /**
     * 职位信息
     * @return HasOne
     */
    public function jobPositionInfo(): HasOne
    {
        return $this->HasOne(JobpositionModel::class, 'id', 'job_position_id');
    }

    /**
     * 广场岗位列表
     * @return HasMany
     */
    public function AreaList(): HasMany
    {
        return $this->HasMany(AreaJobPositionModel::class, 'id', 'plaza_id');
    }
}
